package com.spring.jms.queue;

import com.spring.jms.model.Spittle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.support.JmsUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

@Service
public class AlertServiceImpl implements AlertService {
	@Autowired
	private JmsTemplate jmsTemplate;
	public void sendSpittleAlert(final Spittle spittle) {
		jmsTemplate.send(
				new MessageCreator() {
					public Message createMessage(Session session)throws JMSException {
						return session.createObjectMessage(spittle);
					}
				});

	}
	
	public Spittle receiveSpittleAlert() {
		try {
			ObjectMessage receivedMessage = (ObjectMessage) jmsTemplate.receive();
			return (Spittle) receivedMessage.getObject();
		} catch (JMSException jmsException) {
			throw JmsUtils.convertJmsAccessException(jmsException);
		}
	}

}

